package com.suo.image;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import net.tsz.afinal.FinalBitmap;

import cn.waps.AppConnect;

import com.suo.demo.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends BaseActivity {

//	private Button getImage;
//	private ImageView image1;
//	private ImageView image2;
//	private ImageView image3;
//	
//	private String[] url;
//	private String[] text;
	private List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
	
	private MyGridView imageGridView;
	private Button more;
	private ImageGridViewAdapter adapter;
	
	public static int width, height;
	private int page = 8;
	private ImageUrl data;
	private ProgressDialog progressDialog;
	private FinalBitmap fb;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		AppConnect.getInstance("0df9931685622b433b8e42ee34524104","default",this);
		findViews();
		getScreenSize();
		setLayoutParams();
		
		data = new ImageUrl(this);
		listItems = data.getImageObj(page);
		page--;
//		url = data.url;
//		text = data.text;
		fb = FinalBitmap.create(this);
		fb.configLoadingImage(R.drawable.default_image);
		adapter = new ImageGridViewAdapter(this, listItems, fb);
		imageGridView.setAdapter(adapter);
	}
	
	private void findViews()
	{
		imageGridView = (MyGridView) findViewById(R.id.imageGridView);
		more = (Button) findViewById(R.id.more);
		more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
				if(page > 0)
				{
					templist = data.getImageObj(page);
					if(templist != null){
						for(int i=0; i<ImageUrl.SIZE_OF_PAGE; i++)
						{
							listItems.add(templist.get(i));
						}
						adapter.notifyDataSetChanged();
						page--;
					}else{
						Toast.makeText(MainActivity.this, "no more", 3000).show();
					}
				}
				else
				{
					Toast.makeText(MainActivity.this, "no more", 3000).show();
				}
				
			}
		});
		imageGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(MainActivity.this, PictureContent.class);
				intent.putExtra("position", arg2);
				intent.putExtra("title", listItems.get(arg2).get("text").toString());
				startActivity(intent);
			}
		});
	}

	private void getScreenSize()
	{
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		width = dm.widthPixels;
		height = dm.heightPixels;
	}
	
	private void setLayoutParams()
	{
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) imageGridView.getLayoutParams();
		lp.setMargins(width/60, width/60, width/60, width/60);
		imageGridView.setLayoutParams(lp);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			progressDialog = new ProgressDialog(MainActivity.this);
			progressDialog.setMessage("正在清除,请稍后..");
			progressDialog.show();
			File file = new File(Pub.getBaseDir() + "image/");
			clearData(file);
			mEditor.clear();
			mEditor.commit();
			progressDialog.dismiss();
			Toast.makeText(MainActivity.this, "清除成功..", Toast.LENGTH_LONG).show();
			break;
		case R.id.menu_settings2:
			AppConnect.getInstance(MainActivity.this).showOffers(MainActivity.this);
			break;
		case R.id.menu_settings3:
			AppConnect.getInstance(MainActivity.this).showFeedback(MainActivity.this);
			break;
		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}

	private void clearData(File file)
	{
		if (file.exists()) { // �ж��ļ��Ƿ����
			if (file.isFile()) { // �ж��Ƿ����ļ�
				file.delete(); // delete()���� ��Ӧ��֪�� ��ɾ�����˼;
			} else if (file.isDirectory()) { // �����������һ��Ŀ¼
				File files[] = file.listFiles(); // ����Ŀ¼�����е��ļ� files[];
				for (int i = 0; i < files.length; i++) { // ����Ŀ¼�����е��ļ�
					this.clearData(files[i]); // ��ÿ���ļ� ������������е��
				}
			}
			file.delete();
		}else{
			
		}
	}

	private static Boolean isExit = false; 
	private static Boolean hasTask = false;   
	Timer tExit = new Timer();    
	TimerTask task = new TimerTask() {           
	   @Override         
	   public void run() {             
	      isExit = false;            
	      hasTask = true;       
	      } 
	   }; 
	     
	   @Override     
	   public boolean onKeyDown(int keyCode, KeyEvent event) {        
	       System.out.println("TabHost_Index.java onKeyDown");      
	       if (keyCode == KeyEvent.KEYCODE_BACK) {           
	       if(isExit == false ) {               
	       isExit = true;            
	       Toast.makeText(this, "再按一次后退键退出应用程序", Toast.LENGTH_SHORT).show();              
	       if(!hasTask) {                    
	        tExit.schedule(task, 2000);               
	       } 
	            } else {                 
	            finish(); 
	            System.exit(0);            
	               } 
	        } 
	        return false;   
	        } 

}
